package com.basic.ui.view

import com.basic.net.ApiResponse
import com.basic.ui.vproperty.Func1

/**
 * @author Peter Liu
 * @since 2023/6/19 23:47
 *
 */
interface IStateView {
    fun showError(msg: String? = null, code: String? = null)
    fun showLoading(show: Boolean = true, msg: String? = null)
    fun showEmpty(msg: String? = null)

    fun showEmpty(result: ApiResponse<*>) {
        showEmpty(result.msg)
    }

    fun showError(result: ApiResponse<*>) {
        showError(result.code, result.msg)
    }

    /**
     * 当要显示正常状态时，IStateView 通过该方法清理状态 如 set Visibility = gone
     */
    fun showNormal()
}

open class StateObserver<T>(stateView: IStateView, val onSuccess: Func1<T>? = null) :
    IStateView by stateView,
    Func1<ApiResponse<T>> {
    override fun invoke(result: ApiResponse<T>?) {
        this.showLoading(false)
        if (result == null) {
            this.showError()
        } else if (result.isSuccess()) {
            if (result.isDataEmpty()) {
                this.showEmpty(result)
            } else {
                showNormal()
                showData(result.result!!)
            }
        } else {
            this.showError(result)
        }
    }

    fun showData(data: T) {
        onSuccess?.invoke(data)
    }

}